package com.zcsy.manage.owner.controller.ownercenter;


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyun.oss.OSSClient;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.OwnerConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.upload.AliyunOssUtil;
import com.zcsy.commons.upload.FileUploadUtil;
import com.zcsy.commons.upload.FileUploadUtil.UploadFileItem;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.commons.util.Globals;
import com.zcsy.commons.util.PropertiesUtil;
import com.zcsy.manage.model.base.CommonToken;
import com.zcsy.manage.model.base.OwnerHouse;
import com.zcsy.manage.model.base.ShopCategory;
import com.zcsy.manage.model.base.ShopInfo;
import com.zcsy.manage.model.mall.CouponDetail;
import com.zcsy.manage.model.mall.CouponInfo;
import com.zcsy.manage.model.mall.GoodsInfo;
import com.zcsy.manage.model.mall.IntegralCategory;
import com.zcsy.manage.model.mall.IntegralConfig;
import com.zcsy.manage.model.mall.IntegralRecord;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.owner.service.common.IOCommonTokenService;
import com.zcsy.manage.service.base.ICellHouseService;
import com.zcsy.manage.service.base.IShopCategoryService;
import com.zcsy.manage.service.base.IShopInfoService;
import com.zcsy.manage.service.mall.ICouponDetailService;
import com.zcsy.manage.service.mall.ICouponInfoService;
import com.zcsy.manage.service.mall.IGoodsInfoService;
import com.zcsy.manage.service.mall.IIntegralCategoryService;
import com.zcsy.manage.service.mall.IIntegralConfigService;
import com.zcsy.manage.service.mall.IIntegralRecordService;
import com.zcsy.manage.service.system.IUserService;


/**
 * @Title: NewsController.java
 * @Package： com.hslt.manage.distribution.controller.news
 * @Description:我的控制层
 * @author yangfan 373188993@qq.com
 * @Copyright: 2016 武汉恒数利通信息技术有限公司 All rights reserved.
 * @date 2016年6月30日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */

@Controller
@RequestMapping(value = "owner")
public class OwnerCenterController {

    @Autowired
    private IOCommonTokenService commomTokenService;

    @Autowired
    private ICouponInfoService couponInfoService;
    
    @Autowired
    private ICouponDetailService couponDetailService;

    @Autowired
    private IGoodsInfoService goodsInfoService;

    @Autowired
    private IIntegralRecordService integralRecordService;
    
    @Autowired
    private IIntegralConfigService integralConfigService;
    
    @Autowired
    private IIntegralCategoryService integralCategoryService;

    @Autowired
    private IUserService userService;

    @Autowired
    private ICellHouseService cellHouseService;
    
    @Autowired
    private IShopCategoryService shopCategoryService;
    
    @Autowired
    private IShopInfoService shopInfoService;
    
    private static PropertiesUtil propertiesUtil=new PropertiesUtil("config.properties");
    
    private static String endpoint = propertiesUtil.getProperty("OSS_ENDPOINT");
    private static String accessId= propertiesUtil.getProperty("ACCESS_ID");
    private static String accessKey= propertiesUtil.getProperty("ACCESS_KEY");
    private static String bucketName= propertiesUtil.getProperty("bucketName");

    /**
     * @Description 优惠券列表查询
     * @param token
     *            couponState优惠券状态
     * @return result优惠券信息列表
     * @author yangfan 373188993@qq.com
     * @date 2016年6月30日
     */
    @RequestMapping(value = "getCouponList")
    @ResponseBody
    public RequestJson getCouponList(String token, Integer couponState ,Integer pNo) {

        RequestJson result = new RequestJson();
        
        try {
            // 指定默认为首页
            if (pNo == null || pNo < OwnerConstants.PAGE_NO) {
                pNo = OwnerConstants.PAGE_NO;
            }
            
            // 根据token取出user_account
            CommonToken tokenInfo = commomTokenService.selectByToken(token);
            String userAccount = tokenInfo.getAccount();
            
            CouponInfo couponInfo = new CouponInfo();
            couponInfo.setUserAccount(userAccount);
            couponInfo.setCouponState(couponState);
            
            //取出已使用，未使用，已过期的优惠券数量
            CouponDetail couponDetailCount = couponDetailService.getCouponDetailCount(userAccount);
            
            // 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
            PageHelper.startPage(pNo, OwnerConstants.PAGE_SIZE);
            
            List<CouponInfo> couponInfoList = couponInfoService.selectByUserAccountAndState(couponInfo);
            PageInfo<CouponInfo> couponInfoListP = new PageInfo<CouponInfo>(couponInfoList);
            
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("couponDetailCount", couponDetailCount);
            map.put("couponInfoListP", couponInfoListP);
            
            if (!couponInfoList.isEmpty()) {
                result.setSuccess(true);
                result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                result.setMsg("查看成功！");
                result.setObj(map);
            } else {
                result.setSuccess(false);
                result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
                result.setMsg("无数据！");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常");
        }

        return result;

    }

    /**
     * @Description 获取积分商品列表
     * @param token
     * @param pNo 分页
     * @param integralStart 积分起始
     * @param integralEnd 积分结束
     * @param sortType
     *            =1 按综合排序(不排序) =2 按积分排序 =3 按销量排序
     * @return result积分商品列表
     * @author liuziyu
     * @date 2016年6月30日
     */
    @RequestMapping(value = "getIntegralGoods")
    @ResponseBody
	public RequestJson getIntegralGoods(Integer pNo, String token,
			String sortType, String integralStart, String integralEnd) {

		RequestJson result = new RequestJson();

		// 指定默认为首页
		if (pNo == null || pNo < OwnerConstants.PAGE_NO) {
			pNo = OwnerConstants.PAGE_NO;
		}

		// 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
		PageHelper.startPage(pNo, OwnerConstants.PAGE_SIZE);

		// 查询平台中的商品，可根据积分、销量大小排序
		Map<String, String> map = new HashMap<String, String>();
		map.put("sortType", sortType);
		map.put("integralStart", integralStart);
		map.put("integralEnd", integralEnd);
		List<GoodsInfo> goodsInfoList = goodsInfoService
				.getIntegralGoodsInfo(map);
		if (!goodsInfoList.isEmpty()) {
			// 分页
			PageInfo<GoodsInfo> goodsInfoListP = new PageInfo<GoodsInfo>(
					goodsInfoList);
			result.setSuccess(true);
			result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
			result.setMsg("查看成功！");
			result.setObj(goodsInfoListP);
		} else {
			result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
			result.setMsg("无此积分区间的商品！");
			result.setSuccess(false);

		}

		return result;

	}

    /**
     * @Description 获取积分记录列表
     * @param token
     * @return result获取积分记录列表
     * @author yangfan 373188993@qq.com
     * @date 2016年7月1日
     */
    @RequestMapping(value = "getIntegralList")
    @ResponseBody
    public RequestJson getIntegralList(String token) {

        RequestJson result = new RequestJson();

        try {
            // 根据token查询用户名
            CommonToken tokenInfo = commomTokenService.selectByToken(token);
            String userAccount = tokenInfo.getAccount();
            IntegralRecord integralRecord = new IntegralRecord();
            
            // 根据integralRecord查询所需信息
            integralRecord.setUserAccount(userAccount);
            List<IntegralRecord> integralRecordList = integralRecordService.selectByUserAccount(integralRecord);
            
            if (!integralRecordList.isEmpty()) {
                result.setSuccess(true);
                result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                result.setMsg("获取积分列表成功！");
                result.setObj(integralRecordList);
            } else {
                result.setSuccess(false);
                result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
                result.setMsg("获取积分列表失败！");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常");
        }

        return result;

    }

    /**
     * @Description 获取我的房屋列表
     * @param token
     * @return result我的房屋列表
     * @author yangfan 373188993@qq.com
     * @date 2016年7月1日
     */
    @RequestMapping(value = "getMyHouseList")
    @ResponseBody
    public RequestJson getMyHouseList(String token) {

        RequestJson result = new RequestJson();

        try {
            // 根据token查询loginname
            CommonToken tokenInfo = commomTokenService.selectByToken(token);
            String loginname = tokenInfo.getAccount();
            User user = userService.selectByLoginName(loginname);
            String ownerId = user.getId();
            
            // 根据ownerId查询所需信息,返回列表
            List<OwnerHouse> ownerHouseList = cellHouseService.getMyHouseList(ownerId);
            
            if (!ownerHouseList.isEmpty()) {
                result.setSuccess(true);
                result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                result.setMsg("获取房屋成功！");
                result.setObj(ownerHouseList);
            } else {
                result.setSuccess(false);
                result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
                result.setMsg("获取房屋失败！");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常");
        }

        return result;

    }
    
    /**
     * @Description 房屋注销
     * @param token
     * @param houseId 房屋id
     * @return 1： 注销成功  2：注销失败
     * @author yangfan 373188993@qq.com
     * @date 2016年7月1日
     */
    @RequestMapping(value = "houseCancellation")
    @ResponseBody
    public RequestJson houseCancellation(String token , String houseId) {

        RequestJson result = new RequestJson();
        try {
            CommonToken tokenInfo = commomTokenService.selectByToken(token);
            String loginname = tokenInfo.getAccount();
            User user = userService.selectByLoginName(loginname);
            String ownerId = user.getId();
            
            Integer flag = cellHouseService.deleteOwnerHouseByHouseId(houseId , ownerId);
            if(flag == OwnerConstants.DELETE_SUCCESS) {
                result.setSuccess(true);
                result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                result.setMsg("注销成功！");
            } else if(flag == OwnerConstants.DELETE_FALSE) {
                result.setSuccess(false);
                result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
                result.setMsg("注销失败！");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常");
        }
        
        return result;
        
    }
    
    
    /**
     * @Description <br>
     * 1、…<br>
     * 2、…<br>
     * 
     * @param token
     * @return 
     * @author caiyinli 13277030520@163.com
     * @date 2016年7月7日
     * @see 
     */
    @RequestMapping(value = "uploadHeadPic", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson uploadHeadPic(String token,HttpServletRequest req) {

        RequestJson result = new RequestJson();
        Integer fileId = 0;  
        try {
        	 OSSClient client = new  OSSClient(endpoint,accessId,accessKey); 
//            res.setContentType("text/html");
            final UploadFileItem[] uploadFiles = FileUploadUtil.saveUploadFile(req);

            File file = uploadFiles[0].getInternalFile();

          //图片上传至阿里云服务器
            Map<String, Object> returnmap = AliyunOssUtil.uploadFile(client,bucketName, file.getName(),file); 
            String headimgUrl = (String)returnmap.get("objectkey");
            
          //通过token获取用户信息
			CommonToken tokenInfo = commomTokenService.selectByToken(token);
			String loginname = tokenInfo.getAccount();
			User user = userService.selectByLoginName(loginname);
			
			if(user != null){
				user.setHeadimg(headimgUrl);
				int flag = userService.updateByPrimaryKeySelective(user);
				if(flag == Constants.SQL_RESULT_SUCCESS){
					result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
		            result.setMsg("头像上传成功！");
		            result.setObj(user);
				}else {
					result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
		            result.setMsg("头像上传失败！");
				}
			}
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            result.setMsg("操作异常");
            result.setSuccess(false);
        }
        
        return result;
        
    }
    
    /**
     * @Description 获取店铺类型列表
     * @param token
     * @return result店铺类型列表
     * @author yangfan 373188993@qq.com
     * @date 2016年7月1日
     */
    @RequestMapping(value = "getShopCategory")
    @ResponseBody
    public RequestJson getShopCategory() {

        RequestJson result = new RequestJson();
        
        try {
            //查询店铺类型名称
            List<ShopCategory> shopCategory = shopCategoryService.getAllShopcategory();
            
            if (!shopCategory.isEmpty()) {
                result.setSuccess(true);
                result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                result.setMsg("查询成功！");
                result.setObj(shopCategory);
            } else {
                result.setSuccess(false);
                result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
                result.setMsg("查询失败！");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常");
        }

        return result;

    }
    
    /**
     * @Description 提交商户入驻信息
     * @param token            标记
     *        shopCategoryId   店铺类型id
     *        contactor        联系人
     *        contactorPhone   联系电话
     *        businessRange    经营范围
     *        cellId           小区id
     *        provinceId       省id
     *        cityId           市id
     * @return result店铺类型列表
     * @author yangfan 373188993@qq.com
     * @date 2016年7月1日
     */
    @RequestMapping(value = "submitShopAccount")
    @ResponseBody
    public RequestJson submitShopAccount(String token, String shopCategoryId, String contactor,
                                         String contactorPhone, String businessRange,
                                         String cellId, Integer provinceId, Integer cityId) {

        RequestJson result = new RequestJson();
        ShopInfo shopInfo = new ShopInfo();

        try {
            // 生成18位id
            String id = UniqueNumberUtils.get18UniqueNumber();
            
            if ((null != shopCategoryId) && (null != contactor) && (null != contactorPhone)
                && (null != businessRange) && (null != cellId) && (null != provinceId)
                && (null != cityId)) {
                // 将传入的信息赋给shopInfo对象
                shopInfo.setId(id);
                shopInfo.setShopCategoryId(shopCategoryId);
                shopInfo.setContactor(contactor);
                shopInfo.setContactor(contactorPhone);
                shopInfo.setBusinessRange(businessRange);
                shopInfo.setCellId(cellId);
                shopInfo.setProvinceId(provinceId);
                shopInfo.setCityId(cityId);
                // 设置店铺状态：public static final int SHOP_STATE_NEW = 1; 新申请
                shopInfo.setState(Constants.SHOP_STATE_NEW);
                
                // 插入数据，1:成功 0:失败
                int flag = shopInfoService.insert(shopInfo);
                
                if (flag == OwnerConstants.INSERT_SUCCESS) {
                    result.setSuccess(true);
                    result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                    result.setMsg("提交申请成功！请耐心等待审核！");
                } else {
                    result.setSuccess(false);
                    result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                    result.setMsg("保存数据失败！");
                }
            } else {
                result.setSuccess(false);
                result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                result.setMsg("相关数据未填写完整！");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常");
        }
        return result;

    }
    
    /**
     * @Description 积分增加接口
     * @param token
     *        integralName 积分配置名称(英文)
     * @return result成功或失败
     * @author yangfan 373188993@qq.com
     * @date 2016年7月10日
     */
    @RequestMapping(value = "AddIntegral")
    @ResponseBody
    public RequestJson AddIntegral(String token, String integralName) {

        RequestJson result = new RequestJson();

        try {
            // 根据token查询用户名
            CommonToken tokenInfo = commomTokenService.selectByToken(token);
            String userAccount = tokenInfo.getAccount();
            
            // 根据积分配置名字取label
            IntegralConfig integralConfig = integralConfigService.selectByName(integralName);
            String description = integralConfig.getLabel();
            
            // 根据userAccount和integralName查询最近一条积分打卡记录
            IntegralRecord integralRecord = new IntegralRecord();
            integralRecord.setDescription(description);
            integralRecord.setUserAccount(userAccount);
            IntegralRecord record = integralRecordService.selectLastRecordByUserAccountAndDespription(integralRecord);
            
            if (record != null) {
                // 取上一次打卡时间，当日开始时间，当日结束时间
                record.getRecordTime();
                Date startTime = DateUtils.getStartTimeOfDay();
                Date endTime = DateUtils.getEndTimeOfDay();
                
                // 限定一天打卡一次
                if ((record.getRecordTime().after(startTime))
                    && (record.getRecordTime().before(endTime))) {
                    result.setSuccess(false);
                    result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                    result.setMsg("今日已签到！");
                } else {
                    // 调用AddIntegralMethod方法增加积分
                    int flag = integralRecordService.changeIntegralMethod(userAccount, integralName);
                    if (flag == OwnerConstants.INSERT_SUCCESS) {
                        result.setSuccess(true);
                        result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                        result.setMsg("打卡成功！");
                    }
                }
            } else {
            	// 调用AddIntegralMethod方法增加积分
                int flag = integralRecordService.changeIntegralMethod(userAccount, integralName);
                if (flag == OwnerConstants.INSERT_SUCCESS) {
                    result.setSuccess(true);
                    result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                    result.setMsg("打卡成功！");
                }
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常");
        }
        return result;
    }
    
    /**
     * @Method: integralClassify
     * @Description 积分专区分类接口
     * @param token
     * @return 
     * @author liuziyu liuziyuwri@foxmail.com
     * @date 2016年7月11日
     * @see 
     */
    @RequestMapping(value = "integralClassify")
    @ResponseBody
	public RequestJson integralClassify(String token) {

		RequestJson result = new RequestJson();
		// 查询所有分区
		List<IntegralCategory> integralCategory = integralCategoryService.selectAll();

		if (integralCategory !=null && integralCategory.size() > 0) {
			result.setSuccess(true);
            result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
            result.setMsg("积分专区查询成功！");
            result.setObj(integralCategory);
		} else {
			result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
            result.setMsg("积分专区查询失败！");

		}
		return result;
    }
}
